<!-- src/lib/Breadcrumbs.svelte -->
<script lang="ts">
	import { page } from '$app/state';
	import PopoverCascader from '$lib/components/Basic/Popover/PopoverCascader.svelte';
	import { goto } from '$app/navigation';
	import { type Option } from '$lib/components/Basic/Popover/types';
	import Icon from '$lib/components/Basic/Icon/Icon.svelte';

	let activeMenuIndex: number | null = null;
	let triggerRefs: HTMLElement[] = [];
	let lastProcessedPath = ''; // 新增：路径快照

	function findOptionWithParents(options: Option[], targetCode: string): Option[] {
		// 递归遍历函数，path用于记录当前路径（父对象链）
		function dfs(currentOptions: Option[], path: Option[]): Option[] {
			for (const option of currentOptions) {
				// 将当前节点加入路径
				const newPath = [...path, option];

				// 找到目标code，返回完整路径（包含所有父对象和自身）
				if (option.code === targetCode) {
					return newPath;
				}

				// 如果有子节点，递归搜索子节点
				if (option.children && option.children.length > 0) {
					const result = dfs(option.children, newPath);
					// 子节点中找到目标，返回结果
					if (result && result.length > 0) {
						return result;
					}
				}

				// 未找到目标，继续遍历下一个节点（自动回溯路径）
			}
			// 当前层级未找到目标
			return [];
		}

		// 从根节点开始搜索，初始路径为空
		return dfs(options, []);
	}

	// 解析当前路径为面包屑数据
	let breadcrumbs: any[] = [];
	function getBreadcrumbs(path: string) {
		if (lastProcessedPath === path) return breadcrumbs;
		breadcrumbs = findOptionWithParents(page.data.menuItems, path);
		lastProcessedPath = path;
		return breadcrumbs;
	}
	// 显示子菜单
	const showSubmenu = (index: number, event: MouseEvent | KeyboardEvent) => {
		if (index === breadcrumbs.length - 1) return;
		activeMenuIndex = index;
	};

	// 隐藏子菜单
	const hideSubmenu = () => {
		activeMenuIndex = null;
	};

	//
	const clickMenu = (option: Option) => {
		if (option.code && option.code != null && option.code != undefined) {
			goto(option.code);
		} else {
			goto('/home');
		}
	};
</script>

<nav class="breadcrumbs" aria-label="面包屑导航">
	<Icon src="traffic/location" size="18" color="var(--color-info-500)" style="margin-right:6px"
	></Icon>
	{#each getBreadcrumbs(page.url.pathname) as crumb, index (index)}
		<div
			class="crumb-buttons"
			class:crumb-click={index !== breadcrumbs.length - 1}
			class:isActive={activeMenuIndex === index}
			on:click={(e) => {
				showSubmenu(index, e);
			}}
			on:keydown={() => {}}
			role="button"
			tabindex="0"
			bind:this={triggerRefs[index]}
		>
			<span>{crumb.name}</span>
			{#if index !== breadcrumbs.length - 1}
				<Icon src="symbol/arrow-right" size="18"></Icon>
			{/if}
		</div>
		{#if activeMenuIndex != null && activeMenuIndex == index && crumb.children && crumb.children.length > 0}
			<PopoverCascader
				placement="right"
				bind:triggerRef={triggerRefs[index]}
				label="name"
				options={crumb.children}
				onClose={hideSubmenu}
				onChange={clickMenu}
			></PopoverCascader>
		{/if}
	{/each}
</nav>

<style scoped lang="scss">
	.breadcrumbs {
		padding: 0 10px;
		height: 100%;
		display: flex;
		gap: 6px;
		align-items: center;
		font-family: Arial, Helvetica, sans-serif;
		font-weight: 500;
	}
	.crumb-click {
		color: var(--color-info-500);
		cursor: pointer;
		&:hover {
			color: var(--color-primary-500);
			text-decoration: underline;
		}
	}
	.crumb-buttons {
		display: flex;
		align-items: flex-end;
		gap: 6px;
	}
	.isActive {
		color: var(--color-primary-500);
		text-decoration: underline;
	}
</style>
